// pages/course/course.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		head: ['一', '二', '三', '四', '五', '六', '日'],
		left: ["1", "2", "3", "4", "午", "5", "6", "7", "8", "晚", "9", "10", "11"],
		courseList: [],
		show: false,
		courseName: "",
		courseTeacher: "",
		startTime: "",
		endTime: "",
		color: ["#b5ccff", "#b1d3e4", "#e2c0d4", "#f6b8b3", "#babcd81", "#fbd3ab", "#aad4b3", "#b2e0da", "#f8c2c6",
			"#c2c2c2"
		],
		time1: ["8:50", "9:40", "10:40", "11:30", "12:15", "14:00", "14:50", "15:45", "16:35", "17:30", "19:00", "19:50",
			"20:40"
		],
		time2: ["9:35", "10:25", "11:25", "12:15", "14:00", "14:45", "15:35", "16:30", "17:20", "19:00", "19:45", "20:35",
			"21:25"
		],
		hours: [0, 8, 9, 10, 11, 14, 14, 15, 16, 17, 19, 19],
		minutes: [0, 50, 40, 40, 30, 0, 50, 45, 35, 30, 0],
		record: [],
		latest: {},
		over: false,
		myCourseList: [],
		openId: "",

	},

	//点击即将上课的按钮，跳转到课程详情页，可以进行签到
	clickTop: function(e) {
		wx.navigateTo({
			url: '../courseDetail/courseDetail?c_id=' + e.currentTarget.id +
				'&times=' + e.currentTarget.dataset.times +
				'&remain=' + e.currentTarget.dataset.remain +
				'&s_id=' + this.data.openId + '&sign=' 
		})
	},

	//点击全部课程里的某一课程，跳转至课程详情页
	clickCourse: function(e) {
		//console.log(e);
		wx.navigateTo({
			url: '../courseDetail/courseDetail?c_id=' + e.currentTarget.id +
				'&times=' + e.currentTarget.dataset.times +
				'&remain=' + e.currentTarget.dataset.remain +
				'&s_id=' + this.data.openId + '&sign=' + 1
		})
	},

	findLatest: function() {
		var date = new Date();
		var today = date.getDay();
		var hour = date.getHours();
		var list = this.data.myCourseList;
		var temp = list[0];
		for (let i = 1; i < list.length; i++) {
			if (list[i].week < today || (list[i].week === today && this.data.hours[list[i].startTime] < hour))
				//i课程已结束
				continue;
			else if (temp.week < today || (temp.week === today && this.data.hours[temp.startTime] < hour))
			//temp课程已结束
			{
				temp = list[i];
				continue;
			} else if (list[i].week - today > temp.week - today) //两门课都没结束，且i课程比temp课程日期更后
			{
				continue;
			} else if (list[i].week - today < temp.week - today) //i课程日期更前
			{
				temp = list[i];
			} else //两门课同一天
			{
				if (list[i].startTime < temp.startTime) {
					temp = list[i];
					continue;
				} else
					continue;
			}
		}
		console.log(temp);
		if (temp.week < today || (temp.week === today && this.data.hours[temp.startTime] < hour)) {
			this.setData({
				over: true,
				'latest': temp
			});
		} else {
			this.setData({
				'latest': temp
			})
		}
		return
	},

	getCourseList: function() {
		return new Promise((resolve, reject) => {
			var that = this;
			const db = wx.cloud.database();
			// 调用云函数获取openid
			wx.cloud.callFunction({
				name: "login",
				success: res => {
					that.setData({
						openId: res.result.openid
					}, () => {
						//console.log(that.data.openId);
					});
					//数据库查询  一层
					db.collection('CourseSales').where({
						studentID: res.result.openid
					}).get({
						success: resp => {
							//查询进度
							//console.log(res);
							for (let i = 0; i < resp.data.length; i++) {
								let myCourseList = that.data.myCourseList;
								let val = ((resp.data[i].times - resp.data[i].remainingTimes) / resp.data[i].times * 100);
								myCourseList.push({
									progress: val,
									id: resp.data[i].courseId,
									times: resp.data[i].times,
									remainingTimes: resp.data[i].remainingTimes
								});
								that.setData({
									myCourseList: myCourseList
								}, () => {
									//二层查询 -Course表
									db.collection('Course').where({
										_id: that.data.myCourseList[i].id
									}).get({
										success: res => {
											//查询myCourse需要的数据
											console.log(res.data);
											let myCourseList = that.data.myCourseList
											myCourseList[i].name = res.data[0].name;
											myCourseList[i].coach = res.data[0].coach;
											myCourseList[i].poster = res.data[0].posterURL;
											myCourseList[i].week = res.data[0].week;
											myCourseList[i].startTime = res.data[0].startTime;
											myCourseList[i].length = res.data[0].length;
											//let str = "myCourseList[" + i + "]";
											that.setData({
												myCourseList: myCourseList,
											},() =>{
												if (i === resp.data.length - 1) {
												resolve('获取数据库信息成功');
												reject('获取数据库信息失败');
											}
											});
										}
									})
								})
							}
						}
					})
				},
				fail: res => {
					console.log(res);
					return;
				}
			});

		})
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		var that = this;
		this.getCourseList().then(
			res => {
				console.log(res);
				//这里已经set好了本地的myCourseList，可以用
				that.findLatest();
				that.getRecord().then(res=>{
					console.log(res)
				});
			},
			res => {
				console.log(res);
			}
		)
	},

	getRecord(){
		const db = wx.cloud.database();
    var that=this;
    var userInfo=wx.getStorageSync('userInfo')
    return new Promise((resolve,reject)=>{
      db.collection("Record").where({
        studentID:userInfo.openid
      }).get().then(res=>{
        console.log(res.data[0])
        // var sign=res.data[0].signTime
        for(let i=res.data[0].signTime.length-1;i>=0;i--){
          console.log(res.data[0].signTime)
          // console.log(sign[i])
          let record=that.data.record;
          record.push({
            time:res.data[0].signTime[i].day,
            course:[]
          })
         that.setData({
           record:record
         },()=>{

          // for(let index=0;index<that.data.index;index++){
            for(let j=0;j<res.data[0].signTime[i].courseID.length;j++){
              db.collection("Course").doc(res.data[0].signTime[i].courseID[j]).get().then(re=>{
                let record=that.data.record;
                console.log(record)
                record[i].course.push({
                  name:re.data.name,
                  startTime:re.data.startTime,
                  length:re.data.length
                })
                that.setData({
                  record:record
                },()=>{
                  if(i===res.data[0].signTime.length-1){
                    resolve("成功");
                    reject("失败");
                  }
                }) 
              })
            }
          // }
         })
        }
      })
      
    })
  },
  
  courseDetail(e){
    
    var {index}=e.currentTarget.dataset;
    console.log(index)
    var time1=this.data.time1;
    var time2=this.data.time2
    var myCourseList=this.data.myCourseList;
    this.setData({
      courseName:myCourseList[index].name,
      courseTeacher:myCourseList[index].coach,
      startTime:time1[myCourseList[index].startTime-1],
      endTime:time2[(myCourseList[index].startTime+myCourseList[index].length)-2],
      show:true
    })
	},
	
	onClose() {
		
	},
	onPullDownRefresh(){
		wx.reLaunch({
			url: '/pages/course/course',
		})
	}
})
